import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface CartItem {
  id: string; // 购物车项目的唯一ID
  materialId: number;
  materialName: string;
  storeTypeId: number;
  storeTypeName: string;
  unit: string;
  price: number;
  quantity: number;
  maxStock: number;
  availableStock: number;
  // 申请相关字段（可选）
  statusNewOrChange?: number; // 申请类型：1=新增，2=更新
  receiverId?: number; // 接收人ID
  receiverName?: string; // 接收人姓名
  receiverDept?: string; // 接收人部门
  expectedDate?: Date; // 预期时间
}

export const useCartStore = defineStore('cart', () => {
  // 入库购物车
  const inboundItems = ref<CartItem[]>([]);
  // 出库购物车
  const outboundItems = ref<CartItem[]>([]);
  
  // 入库购物车计算属性
  const inboundTotal = computed(() => inboundItems.value.length);
  const inboundQuantity = computed(() => inboundItems.value.reduce((sum, item) => sum + item.quantity, 0));
  const inboundAmount = computed(() => inboundItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0));
  
  // 出库购物车计算属性
  const outboundTotal = computed(() => outboundItems.value.length);
  const outboundQuantity = computed(() => outboundItems.value.reduce((sum, item) => sum + item.quantity, 0));
  const outboundAmount = computed(() => outboundItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0));

  // 生成购物车项目ID
  const generateCartItemId = (materialId: number, type: 'inbound' | 'outbound') => {
    return `${type}_${materialId}_${Date.now()}`;
  };

  // 添加到入库购物车
  const addToInboundCart = (materials: Omit<CartItem, 'id'>[]) => {
    const addedItems: { name: string; quantity: number; isNew: boolean }[] = [];
    
    materials.forEach(material => {
      // 检查是否已存在相同物资
      const existingIndex = inboundItems.value.findIndex(item => item.materialId === material.materialId);
      if (existingIndex >= 0) {
        // 合并数量
        inboundItems.value[existingIndex].quantity += material.quantity;
        addedItems.push({
          name: material.materialName,
          quantity: material.quantity,
          isNew: false
        });
      } else {
        // 添加新项目
        inboundItems.value.push({
          ...material,
          id: generateCartItemId(material.materialId, 'inbound'),
        });
        addedItems.push({
          name: material.materialName,
          quantity: material.quantity,
          isNew: true
        });
      }
    });
    
    return addedItems;
  };

  // 添加到出库购物车
  const addToOutboundCart = (materials: Omit<CartItem, 'id'>[]) => {
    const addedItems: { name: string; quantity: number; isNew: boolean }[] = [];
    
    materials.forEach(material => {
      // 检查是否已存在相同物资
      const existingIndex = outboundItems.value.findIndex(item => item.materialId === material.materialId);
      if (existingIndex >= 0) {
        // 合并数量
        outboundItems.value[existingIndex].quantity += material.quantity;
        addedItems.push({
          name: material.materialName,
          quantity: material.quantity,
          isNew: false
        });
      } else {
        // 添加新项目
        outboundItems.value.push({
          ...material,
          id: generateCartItemId(material.materialId, 'outbound'),
        });
        addedItems.push({
          name: material.materialName,
          quantity: material.quantity,
          isNew: true
        });
      }
    });
    
    return addedItems;
  };

  // 更新入库购物车项目数量
  const updateInboundQuantity = (id: string, quantity: number) => {
    const item = inboundItems.value.find(item => item.id === id);
    if (item) {
      item.quantity = Math.max(1, quantity); // 入库没有上限限制
    }
  };

  // 更新入库购物车项目属性
  const updateInboundItemProperty = (id: string, property: keyof CartItem, value: any) => {
    const item = inboundItems.value.find(item => item.id === id);
    if (item) {
      (item as any)[property] = value;
    }
  };

  // 更新出库购物车项目数量
  const updateOutboundQuantity = (id: string, quantity: number) => {
    const item = outboundItems.value.find(item => item.id === id);
    if (item) {
      item.quantity = Math.max(1, Math.min(quantity, item.availableStock));
    }
  };

  // 从入库购物车移除项目
  const removeFromInboundCart = (id: string) => {
    const index = inboundItems.value.findIndex(item => item.id === id);
    if (index >= 0) {
      inboundItems.value.splice(index, 1);
    }
  };

  // 从出库购物车移除项目
  const removeFromOutboundCart = (id: string) => {
    const index = outboundItems.value.findIndex(item => item.id === id);
    if (index >= 0) {
      outboundItems.value.splice(index, 1);
    }
  };

  // 清空入库购物车
  const clearInboundCart = () => {
    inboundItems.value = [];
  };

  // 清空出库购物车
  const clearOutboundCart = () => {
    outboundItems.value = [];
  };

  // 保存入库购物车到本地存储
  const saveInboundToLocal = () => {
    try {
      localStorage.setItem('inbound_cart_items', JSON.stringify(inboundItems.value));
      return true;
    } catch (error) {
      console.error('保存入库购物车失败:', error);
      return false;
    }
  };

  // 保存出库购物车到本地存储
  const saveOutboundToLocal = () => {
    try {
      localStorage.setItem('outbound_cart_items', JSON.stringify(outboundItems.value));
      return true;
    } catch (error) {
      console.error('保存出库购物车失败:', error);
      return false;
    }
  };

  // 从本地存储加载入库购物车
  const loadInboundFromLocal = () => {
    try {
      const saved = localStorage.getItem('inbound_cart_items');
      if (saved) {
        const items = JSON.parse(saved);
        if (Array.isArray(items)) {
          inboundItems.value = items;
          return items.length;
        }
      }
      return 0;
    } catch (error) {
      console.error('加载入库购物车失败:', error);
      return 0;
    }
  };

  // 从本地存储加载出库购物车
  const loadOutboundFromLocal = () => {
    try {
      const saved = localStorage.getItem('outbound_cart_items');
      if (saved) {
        const items = JSON.parse(saved);
        if (Array.isArray(items)) {
          outboundItems.value = items;
          return items.length;
        }
      }
      return 0;
    } catch (error) {
      console.error('加载出库购物车失败:', error);
      return 0;
    }
  };

  // 清除本地存储的入库购物车
  const clearInboundLocal = () => {
    localStorage.removeItem('inbound_cart_items');
  };

  // 清除本地存储的出库购物车
  const clearOutboundLocal = () => {
    localStorage.removeItem('outbound_cart_items');
  };

  return {
    // 状态
    inboundItems,
    outboundItems,
    
    // 计算属性
    inboundTotal,
    inboundQuantity,
    inboundAmount,
    outboundTotal,
    outboundQuantity,
    outboundAmount,
    
    // 方法
    addToInboundCart,
    addToOutboundCart,
    updateInboundQuantity,
    updateInboundItemProperty,
    updateOutboundQuantity,
    removeFromInboundCart,
    removeFromOutboundCart,
    clearInboundCart,
    clearOutboundCart,
    saveInboundToLocal,
    saveOutboundToLocal,
    loadInboundFromLocal,
    loadOutboundFromLocal,
    clearInboundLocal,
    clearOutboundLocal,
  };
});